package com.suhui.task.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.suhui.task.common.Result;
import com.suhui.task.pojo.Member_Progress;
import com.suhui.task.pojo.Progress;
import com.suhui.task.pojo.Task;
import com.suhui.task.pojo.progress.M;
import com.suhui.task.pojo.progress.P;
import com.suhui.task.pojo.progress.P_M;
import com.suhui.task.pojo.progress.P_all;
import com.suhui.task.service.Get_header;
import com.suhui.task.service.HttpRequest;
import com.suhui.task.service.My_util;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RequestMapping("/progress")
@RestController
public class ProgressController {

    private String URL = "http://172.16.249.145:5000/shproject_task";
//    private String URL = "http://192.168.136.131:3000";

    @Resource
    private HttpRequest httpRequest;

    @Resource
    private Get_header get_header;

    @Resource
    private My_util my_util;

    /**
     * 进度信息页面
     * 分页查询
     * 获取 成员数据
     */
    @GetMapping("/get_member")
    public Result<?> progress_data(String url,int limit,String order) {
        if ("".equals(url)){
            return Result.error("500","请求格式错误");
        }
        if (0 >= limit) {
            // 一页默认数据为 8 条
            limit = 8;
        }
        if ("".equals(order)) {
            // 默认按id 分页
            order = "id";
        }
        Map<String,Object> param = new HashMap<>();
        param.put("limit",limit);
        param.put("order",order);
        url = this.URL + url;
        // 拿到有token的请求头
        Map<String,String> header = get_header.set_header();
        String data_s = httpRequest.sendGet(url,param,header);
        // 将获取的数据 字符串 转换为 json格式的集合
        JSONArray data_array = JSON.parseArray(data_s);
        return Result.success(data_array);
    }

    /**
     * 进度信息页面
     * 普通表格查询
     * 获取总成员数量
     */
    @GetMapping("/get_member_num")
    public Result<?> progress_data_total(String url) {
        if ("".equals(url)){
            return Result.error("500","请求格式错误");
        }
        url = this.URL + url;
        // 拿到有token的请求头
        Map<String,String> header = get_header.set_header();
        String data_s = httpRequest.sendGet(url,null,header);
        JSONArray data_array = JSON.parseArray(data_s);
        int total = data_array.size();
        return Result.success(total);
    }

    /**
     * 进度信息页面
     * 模糊查询
     * 按指定内容搜索数据
     */
    @GetMapping("/search")
    private Result<?> progress_search(String url,String name,String group) {
        if ("".equals(url)){
            return Result.error("500","请求格式错误");
        }
        if (name==null && group==null) {
            return Result.error("500","未指定姓名或组别");
        }
        url = this.URL + url;
        Map<String,Object> param = new HashMap<>();
        if (name!=null && group==null) {
            String like_name = "like.*" + name + "*";
            param.put("name",like_name);
        }
        if (name==null && group!=null) {
            String like_group = "like.*" + group + "*";
            param.put("group",like_group);
        }
        if (name!=null && group!=null) {
            String like_group = "like.*" + group + "*";
            String like_name = "like.*" + name + "*";
            param.put("group",like_group);
            param.put("name",like_name);
        }
        // 拿到有token的请求头
        Map<String,String> header = get_header.set_header();
        String data_string = httpRequest.sendGet(url,param,header);
        // 将获取的数据 字符串 转换为 json格式的集合
        JSONArray data_array = JSON.parseArray(data_string);
        return Result.success(data_array);
    }

    /**
     * 进度信息页面
     * 条件查询
     * 依据id 获取具体的 成员进度 数据
     */
    @GetMapping("/progress_data_byId")
    public Result<?> progress_data_byId(String id,String url,String select,String order) {
        if (url == null) {
            return Result.error("500","无效的请求路劲");
        }
        if (id==null || "".equals(id)) {
            return Result.error("500","无效的成员id");
        }
        id = "eq." + id;
        Map<String,Object> param = new HashMap<>();
        param.put("select",select);
        param.put("id",id);
        url = this.URL + url;
        // 拿到有token的请求头
        Map<String,String> header = get_header.set_header();
        //请求数据
        String data_s = httpRequest.sendGet(url,param,header);
        // 转换json对象
        JSONArray data_array = JSON.parseArray(data_s);
        // 多次对象转换得到最终数据
        JSONArray data = my_util.ChangeData(data_array);
        if (data.isEmpty()) {
            return Result.error("400","暂无数据");
        }
        return Result.success(data);
    }

    /**
     * 进度信息页面
     * 条件查询
     * 依据id 获取具体的 成员信息 数据
     */
    @GetMapping("/progress_member_byId")
    public Result<?> progress_member_byId(String id,String url,String select) {
        if (url == null) {
            return Result.error("500","无效的请求路劲");
        }
        if (id==null || "".equals(id)) {
            return Result.error("500","无效的成员id");
        }
        if (select == null) {
            return Result.error("500","无效的请求路劲");
        }
        id = "eq." + id;
        Map<String,Object> param = new HashMap<>();
        param.put("select",select);
        param.put("id",id);
        url = this.URL + url;
        // 拿到有token的请求头
        Map<String,String> header = get_header.set_header();
        //请求数据
        String data_s = httpRequest.sendGet(url,param,header);
        // 转换json对象
        JSONArray data_array = JSON.parseArray(data_s);
        M m = new M();
        for (Object jsonObject:data_array) {
            m = JSONObject.parseObject(jsonObject.toString(), M.class);
        }
        return Result.success(m);
    }

    /**
     * 进度信息页面
     * 添加数据
     * 添加 进度数据 获取添加的数据id 添加中间表数据
     */
    @PostMapping("/add")
    public Result<?> progress_add(@RequestBody P p) {
        if (p == null) {
            return Result.error("500","无效任务数据");
        }// 时间校验
        Pattern pattern = Pattern.compile("^(\\d{4})年-([1-3][0-9]|0?\\d)周$");
        Matcher matcher = pattern.matcher(p.getYear_week());
        if (!matcher.matches()) {
            return Result.error("500","搜索时间的格式为: xxxx年-x周");
        }
        // 1. 获取成员id（通过name) √
        Map<String, String> header = get_header.set_header();
        String url_member = this.URL + "/member";
        String member_name = "eq." + p.getName();
        HashMap<String, Object> param = new HashMap<>();
        param.put("name",member_name);
        param.put("select","id");
        String data_member = httpRequest.sendGet(url_member, param, header);
        JSONArray jsonArray = JSONArray.parseArray(data_member);
        M m = new M();
        for (Object json_m: jsonArray) {
            m = JSONObject.parseObject(json_m.toString(), M.class);
        }
        String id_member = m.getId();
        // 判断成员是否为空
        if (null == id_member) {
            return Result.error("500","成员不存在，请确定成员姓名");
        }
        // 2. 添加进度信息 √
        Progress progress = my_util.Data_to_progress(p);
        String id_progress_new = my_util.getId(); // 获取进度表中 刚添加的id
        progress.setId(id_progress_new);
        String url_progress = this.URL + "/progress";
        String json_p = JSON.toJSONString(progress);
        httpRequest.sendPost_json_(url_progress, json_p, header);
        // 3.添加中间表数据 √
        Member_Progress member_progress = my_util.Data_to_Member_Progress(p);
        member_progress.setId(my_util.getId()); // 表id
        member_progress.setMember_id(id_member); // 成员id
        member_progress.setProgress_id(id_progress_new); // 进度id
        String url_m_p = this.URL + "/member_progress";
        String json_m_p = JSON.toJSONString(member_progress);
        httpRequest.sendPost_json_(url_m_p, json_m_p, header);
        // 更新成员总的请假次数
            // url-1
        String url_1 = this.URL + "/member_progress?member_id=eq."+id_member+"&select=ask_for_leave";
        String leave_s = httpRequest.sendGet(url_1, null, header);
        JSONArray data_array = JSON.parseArray(leave_s);
            // 拿到总请假次数
        int count_leave = my_util.count_ask_for_leave(data_array);
            // url-2
        String url_2 = this.URL + "/member?id=eq."+id_member;
            // 修改参数
        HashMap<String, Object> param3 = new HashMap<>();
        param3.put("ask_for_leave_all",count_leave);
        httpRequest.sendPatch(url_2, param3, header);
        return Result.success();
    }

    /**
     * 进度管理页面
     * 删除数据
     * 依据进度id删除进度数据
     */
    @DeleteMapping("/delete/{id}")
    public Result<?> progress_delete(@PathVariable String id) {
        if (id == null) {
            return Result.error("500","无效成员id");
        }
        // 请求token
        Map<String, String> header = get_header.set_header();
        // 1. 删除 中间表中的数据 依据进度id（外键原因）
        String url_m_p = this.URL+ "/member_progress?progress_id=eq."+id;
        httpRequest.sendDelete(url_m_p, header);
        // url： 删除进度数据
        String url = this.URL + "/progress?id=eq."+id;
        String s = httpRequest.sendDelete(url, header);
        return Result.success();
    }

    /**
     * 进度管理页面
     * 更新数据
     * 依据进度id更新进度数据
     */
    @PatchMapping("/update")
    public Result<?> progress_update(@RequestBody P_all progress) {
        // 1.更改进度数据
        if (null == progress) {
            return Result.error("500","无效成员数据");
        }
        // 时间校验
        Pattern pattern = Pattern.compile("^(\\d{4})年-([1-3][0-9]|0?\\d)周$");
        Matcher matcher = pattern.matcher(progress.getYear_week());
        if (!matcher.matches()) {
            return Result.error("500","搜索时间的格式为: xxxx年-x周");
        }
        // 请求token
        Map<String, String> header = get_header.set_header();
        // url
        String url = this.URL + "/progress?id=eq."+progress.getId();
        // 数据
        HashMap<String, Object> map_data = new HashMap<>();
        map_data.put("id",progress.getId());
        map_data.put("bool_work",progress.getBool_work());
        map_data.put("bool_overwork",progress.getBool_overwork());
        map_data.put("grasp",progress.getGrasp());
        map_data.put("progress_content",progress.getProgress_content());
        String update_p = httpRequest.sendPatch(url, map_data, header);
        // 2. 更改中间表中的时间数据
        // 2.1 查询中间表的数据 依据id
        String url_q = this.URL+"/member_progress?progress_id=eq."+progress.getId();
        String data_M_P = httpRequest.sendGet(url_q, null, header);
        JSONArray jsonArray = JSON.parseArray(data_M_P);
        HashMap<String, Object> map_m_p = new HashMap<>();
        for (Object ob:jsonArray) {
            Member_Progress m_p = JSON.parseObject(ob.toString(), Member_Progress.class);
            map_m_p.put("id",m_p.getId());
            map_m_p.put("member_id",m_p.getMember_id());
            map_m_p.put("progress_id",m_p.getProgress_id());
            map_m_p.put("year_week",progress.getYear_week());
            map_m_p.put("ask_for_leave",progress.getAsk_for_leave());
        }
        String update_m_p = httpRequest.sendPatch(url_q, map_m_p, header);
        return Result.success();
    }

    /**
     * 进度管理页面
     * 统计 成员表中 总的请假次数
     * 依据成员id 聚合成员每一周的请假次数 统计成员总的请假次数
     */
    @RequestMapping("/update_leave_all")
    public Result<?> update_leave_all(String id) {
        if ("".equals(id) || null == id) {
            return Result.error("500","成员定位错误");
        }
        // 请求token
        Map<String, String> header = get_header.set_header();
        // 1、成员总的请假次数（于中间表）
        // url-1
        String url_1 = this.URL + "/member_progress?member_id=eq."+id+"&select=ask_for_leave";
        String leave_s = httpRequest.sendGet(url_1, null, header);
        JSONArray data_array = JSON.parseArray(leave_s);
        // 拿到总请假次数
        int count_leave = my_util.count_ask_for_leave(data_array);
        // url-2
        String url_2 = this.URL + "/member?id=eq."+id;
        // 修改参数
        HashMap<String, Object> param = new HashMap<>();
        param.put("ask_for_leave_all",count_leave);
        String sendPatch = httpRequest.sendPatch(url_2, param, header);
        return Result.success();
    }

}
